package org.freez4.spring.dependency.inject;

import org.freez4.spring.dependency.inject.domain.UserHolder;
import org.freez4.spring.ioc.overview.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;

import javax.annotation.Resource;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Java 注解方法注入。
 *
 * @author 阿坤同学
 * @date 2023/12/10 23:25
 */
public class AnnotationDependencyMethodInjectionDemo {

    private static final Logger logger = Logger.getLogger(AnnotationDependencyMethodInjectionDemo.class.getName());

    private UserHolder userHolder;

    @Resource
    private UserHolder userHolder2;

    @Autowired
    public void initUserHolder(UserHolder userHolder) {
        this.userHolder = userHolder;
    }

    @Resource
    public void initUserHolder2(UserHolder userHolder) {
        this.userHolder2 = userHolder;
    }


    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        // 注册配置类
        applicationContext.register(AnnotationDependencyMethodInjectionDemo.class);
        // 读取XML BeanDefinition
        XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(applicationContext);
        String location = "classpath:/META-INF/dependency-lookup-context.xml";
        xmlReader.loadBeanDefinitions(location);
        // 刷新上下文
        applicationContext.refresh();

        AnnotationDependencyMethodInjectionDemo fieldInjectionDemo = applicationContext.getBean(AnnotationDependencyMethodInjectionDemo.class);

        logger.log(Level.INFO, () -> "通过方法@Autowired方式注入User对象Demo: " + fieldInjectionDemo.userHolder);
        logger.log(Level.INFO, () -> "通过方法@Resource方式注入User对象Demo: " + fieldInjectionDemo.userHolder2);

        logger.log(Level.INFO, () -> "userHolder 是否与 userHolder2 相等: " + (fieldInjectionDemo.userHolder == fieldInjectionDemo.userHolder2));

        // 关闭容器
        applicationContext.close();
    }

    @Bean
    public UserHolder userHolder(User user) {
        return new UserHolder(user);
    }
}
